//
//  LGTOCBaseUtil.m
//  KJLGT
//
//  Created by jenkin on 2019/8/10.
//  Copyright © 2019年 jenkin. All rights reserved.
//

#import "LGTOCBaseUtil.h"
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CTCarrier.h>
#import <sys/utsname.h>
#import <AdSupport/AdSupport.h>
#import <UIKit/UIKit.h>
#import "AESCrypt.h"
#import<CommonCrypto/CommonDigest.h>

//屏幕宽高
#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height
#define SizeFit(size)   (int)(size * SCREEN_WIDTH / 375.0)
#define UIColorFromRGB(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
//9 以下的没有这个字体 .PingFangSC-Regular
#define ISVersion9 [[UIApplication sharedApplication].version float] < 9.0
#ifdef ISVersion9
#define KNFont(s) [UIFont systemFontOfSize:s]
#else
#define KNFont(s) [UIFont fontWithName:@"PingFangSC-Regular" size:s]
//#define KNFont(s) [UIFont fontWithName:@"MicrosoftYaHei" size:s]
#endif

@implementation LGTOCBaseUtil

+ (NSString *)getPhoneName{
    
    struct utsname systemInfo;
    uname(&systemInfo); NSString *platform = [NSString stringWithCString:systemInfo.machine encoding:NSASCIIStringEncoding];
    //------------------------------iPhone---------------------------
    if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 2G";
    if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
    if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";
    if ([platform isEqualToString:@"iPhone3,1"] || [platform isEqualToString:@"iPhone3,2"] || [platform isEqualToString:@"iPhone3,3"]) return @"iPhone 4";
    if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
    if ([platform isEqualToString:@"iPhone5,1"] || [platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5";
    if ([platform isEqualToString:@"iPhone5,3"] || [platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c";
    if ([platform isEqualToString:@"iPhone6,1"] || [platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s";
    if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6";
    if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus";
    if ([platform isEqualToString:@"iPhone8,1"]) return @"iPhone 6s";
    if ([platform isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus";
    if ([platform isEqualToString:@"iPhone8,4"]) return @"iPhone SE";
    if ([platform isEqualToString:@"iPhone9,1"] || [platform isEqualToString:@"iPhone9,3"]) return @"iPhone 7";
    if ([platform isEqualToString:@"iPhone9,2"] || [platform isEqualToString:@"iPhone9,4"]) return @"iPhone 7 Plus";
    if ([platform isEqualToString:@"iPhone10,1"] || [platform isEqualToString:@"iPhone10,4"]) return @"iPhone 8";
    if ([platform isEqualToString:@"iPhone10,2"] || [platform isEqualToString:@"iPhone10,5"]) return @"iPhone 8 Plus";
    if ([platform isEqualToString:@"iPhone10,3"] || [platform isEqualToString:@"iPhone10,6"]) return @"iPhone X";
    if ([platform isEqualToString:@"iPhone11,8"]) return @"iPhone XR";
    if ([platform isEqualToString:@"iPhone11,2"]) return @"iPhone XS";
    if ([platform isEqualToString:@"iPhone11,4"] || [platform isEqualToString:@"iPhone11,6"]) return @"iPhone XS Max";
    
    //------------------------------iPad--------------------------
    if ([platform isEqualToString:@"iPad1,1"]) return @"iPad";
    if ([platform isEqualToString:@"iPad2,1"] || [platform isEqualToString:@"iPad2,2"] || [platform isEqualToString:@"iPad2,3"] || [platform isEqualToString:@"iPad2,4"]) return @"iPad 2";
    if ([platform isEqualToString:@"iPad3,1"] || [platform isEqualToString:@"iPad3,2"] || [platform isEqualToString:@"iPad3,3"]) return @"iPad 3"; if ([platform isEqualToString:@"iPad3,4"] || [platform isEqualToString:@"iPad3,5"] || [platform isEqualToString:@"iPad3,6"]) return @"iPad 4";
    if ([platform isEqualToString:@"iPad4,1"] || [platform isEqualToString:@"iPad4,2"] || [platform isEqualToString:@"iPad4,3"]) return @"iPad Air"; if ([platform isEqualToString:@"iPad5,3"] || [platform isEqualToString:@"iPad5,4"]) return @"iPad Air 2";
    if ([platform isEqualToString:@"iPad6,3"] || [platform isEqualToString:@"iPad6,4"]) return @"iPad Pro 9.7-inch";
    if ([platform isEqualToString:@"iPad6,7"] || [platform isEqualToString:@"iPad6,8"]) return @"iPad Pro 12.9-inch";
    if ([platform isEqualToString:@"iPad6,11"] || [platform isEqualToString:@"iPad6,12"]) return @"iPad 5";
    if ([platform isEqualToString:@"iPad7,1"] || [platform isEqualToString:@"iPad7,2"]) return @"iPad Pro 12.9-inch 2";
    if ([platform isEqualToString:@"iPad7,3"] || [platform isEqualToString:@"iPad7,4"]) return @"iPad Pro 10.5-inch";
    
    //------------------------------iPad Mini-----------------------
    if ([platform isEqualToString:@"iPad2,5"] || [platform isEqualToString:@"iPad2,6"] || [platform isEqualToString:@"iPad2,7"])
        return @"iPad mini";
    if ([platform isEqualToString:@"iPad4,4"] || [platform isEqualToString:@"iPad4,5"] || [platform isEqualToString:@"iPad4,6"])
        return @"iPad mini 2";
    if ([platform isEqualToString:@"iPad4,7"] || [platform isEqualToString:@"iPad4,8"] || [platform isEqualToString:@"iPad4,9"])
        return @"iPad mini 3";
    if ([platform isEqualToString:@"iPad5,1"] || [platform isEqualToString:@"iPad5,2"])
        return @"iPad mini 4";
    //------------------------------iTouch------------------------
    if ([platform isEqualToString:@"iPod1,1"]) return @"iTouch"; if ([platform isEqualToString:@"iPod2,1"]) return @"iTouch2"; if ([platform isEqualToString:@"iPod3,1"]) return @"iTouch3"; if ([platform isEqualToString:@"iPod4,1"]) return @"iTouch4"; if ([platform isEqualToString:@"iPod5,1"]) return @"iTouch5"; if ([platform isEqualToString:@"iPod7,1"]) return @"iTouch6";
    
    //------------------------------Samulitor-------------------------------------
    if ([platform isEqualToString:@"i386"] || [platform isEqualToString:@"x86_64"]) return @"iPhone Simulator";
    return @"iOS Unknown";
}

+ (BOOL)isSIMInstalled{
    CTTelephonyNetworkInfo *networkInfo = [[CTTelephonyNetworkInfo alloc] init];
    CTCarrier *carrier = [networkInfo subscriberCellularProvider];
    if(!carrier.isoCountryCode){
        NSLog(@"请安装好手机SIM卡后在拨打电话.");
        return NO;
    }else{
        NSLog(@"存在SIM卡");
        return YES;
    }
}

+ (BOOL)checkJailBreak{
    if ([[NSFileManager defaultManager] fileExistsAtPath:@"/Applications/Cydia.app"]){
        return YES;
    }
    
    if([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"cydia://package/com.example.package"]]){
        return YES;
    }
    
    //    if ([[NSFileManager defaultManager] fileExistsAtPath:@"/private/var/lib/apt"]){
    //        return YES;
    //    }
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:@"Library/MobileSubstrate/MobileSubstrate.dylib"]){
        return YES;
    }
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:@"/etc/apt"]){
        return YES;
    }
    
    return NO;
    
}

+ (NSString *)getIDFA{
    return [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
}

+ (void)clearIDFA{
    //[[ASIdentifierManager sharedManager] clearAdvertisingIdentifier];
}

+ (NSDictionary *)getData:(NSDictionary *)data{
    
    NSMutableDictionary *dict = [data mutableCopy];
    //生成签名
    NSArray *keyArray = [LGTOCBaseUtil paixuWith:[[dict allKeys] mutableCopy]];
    NSMutableString *sign = [NSMutableString string];
    for(int i=0; i < keyArray.count; i++){
        NSString *key = keyArray[i];
        [sign appendFormat:@"%@=%@", keyArray[i], dict[key]];
        if(i < (keyArray.count - 1)){
            [sign appendString:@"&"];
        }
    }
    NSString *signKey = @"cdcc221266e6757f4b2b8cb0a7fe5eda";
    [sign appendFormat:@"&key=%@", signKey];
    NSString *_s = [LGTOCBaseUtil md5:sign];
    
    NSLog(@"\nsign\n%@\nsign_md5\n%@", sign, _s);
    [dict setObject:_s forKey:@"_s"];
    
    NSString *aesKey = @"62753003cf97b7d80fb709644aafa1b2";
    NSString *aesIV = @"24643c378a015c86f8349bfd5601dca9";
    
    NSError *parseError = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&parseError];
    NSString *jsonUTF8 = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    NSString *aesStr = [AESCrypt encrypt:jsonUTF8 key:aesKey iv:aesIV];
    [dict removeAllObjects];
    [dict setValue:aesStr forKey:@"_p"];
    
    return dict;
}

//根据拼音的字母排序  ps：排序适用于所有类型
+ (NSMutableArray *)paixuWith:(NSMutableArray *)array{
    [array sortUsingComparator:^NSComparisonResult(NSString *node1, NSString *node2) {
        return [node1 compare:node2];
    }];
    return array;
}


//md5加密
+ (NSString *) md5:(NSString *) input {
    const char *original_str = [input UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(original_str, (CC_LONG)strlen(original_str), result);
    NSMutableString *hash = [NSMutableString string];
    for (int i = 0; i < 16; i++)
        [hash appendFormat:@"%02X", result[i]];
    return [hash lowercaseString];
}

+ (BOOL)ISPHoneX{
    BOOL iphoneX = NO;
    if (UIDevice.currentDevice.userInterfaceIdiom != UIUserInterfaceIdiomPhone) { \
        return iphoneX;
    }

    if (@available(iOS 11.0, *)) {
        UIWindow *mainWindow = [[[UIApplication sharedApplication] delegate] window];
        if (mainWindow.safeAreaInsets.bottom > 0.0) {
            iphoneX = YES;
        }
    }
    return iphoneX;
}

#pragma mark 32-bit lowercase
+ (NSString *)MD5ForLower32Bite:(NSString *)string
{
    //要进行UTF-8的转码
    const char* input = [string UTF8String];
    
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(input, (CC_LONG)strlen(input), result);
    
    NSMutableString *digest = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH *2];
    for (NSInteger i= 0; i<CC_MD5_DIGEST_LENGTH; i++) {
        [digest appendFormat:@"%02x",result[i]];
    }
    
    return digest;
}


//一、压缩图片有两种方式，第一种是压缩图片的大小，重新生成图片的尺寸：如下
/**
 * 压缩图片到指定尺寸大小
 *
 * @param image 原始图片
 * @param size 目标大小
 *
 * @return 生成图片
 */
+ (UIImage *)compressOriginalImage:(UIImage *)image toSize:(CGSize)size{
    UIImage * resultImage = image;
    UIGraphicsBeginImageContext(size);
    [resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
    image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

+ (void)archWithObject:(NSDictionary *)info{
    
//    NSData *data= [NSJSONSerialization dataWithJSONObject:info options:NSJSONWritingPrettyPrinted error:nil];
//
//    NSKeyedArchiver *atch = [NSKeyedArchiver alloc] init
//    [NSKeyedArchiver archivedDataWithRootObject:data requiringSecureCoding:YES error:nil];
//
 //   let filePath:String = NSHomeDirectory() + "/Documents/tfDic.plist"
 
    
   // NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
}


//判断表情
+(BOOL)isContainsEmoji:(NSString *)string {
    __block BOOL isEomji = NO;
    [string enumerateSubstringsInRange:NSMakeRange(0, [string length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:
     ^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
         const unichar hs = [substring characterAtIndex:0];
         if (0xd800 <= hs && hs <= 0xdbff) {
             if (substring.length > 1) {
                 const unichar ls = [substring characterAtIndex:1];
                 const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
                 if (0x1d000 <= uc && uc <= 0x1f77f) {
                     isEomji = YES;
                 }
             }
         } else if (substring.length > 1) {
             const unichar ls = [substring characterAtIndex:1];
             if (ls == 0x20e3) {
                 isEomji = YES;
             }
         } else {
             if (0x2100 <= hs && hs <= 0x27ff && hs != 0x263b) {
                 isEomji = YES;
             } else if (0x2B05 <= hs && hs <= 0x2b07) {
                 isEomji = YES;
             } else if (0x2934 <= hs && hs <= 0x2935) {
                 isEomji = YES;
             } else if (0x3297 <= hs && hs <= 0x3299) {
                 isEomji = YES;
             } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50|| hs == 0x231a ) {
                 isEomji = YES;
             }
         }
     }];
    return isEomji;
}

+ (NSString *)addCookieWithUrl:(NSString *)url data:(NSDictionary *)data type:(NSInteger)type{
    NSMutableDictionary *cookieDic = [data mutableCopy];
    NSHTTPCookie* realCookie = nil;
    NSMutableArray* cookies = [[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies] mutableCopy];
    for (NSHTTPCookie* cookie in cookies) {
        NSRange range = [url rangeOfString:cookie.domain];
        //如过找到了
        if (range.location != NSNotFound) {
            realCookie = cookie;
            break;
        }
    }
    
    if(realCookie != nil){
        NSMutableDictionary *properties = [NSMutableDictionary dictionaryWithDictionary:realCookie.properties];
        [properties setValuesForKeysWithDictionary:cookieDic];
        cookieDic = properties;
    }
    
    NSMutableString *cookieValue = [NSMutableString stringWithFormat:@""];
    if(type == 1){
        for (NSString *key in cookieDic.allKeys) {
            [cookieValue appendFormat:@"%@=%@;", key, cookieDic[key]];
        }
    }else{
        // cookie重复，先放到字典进行去重，再进行拼接
        // js添加cookie
        for (NSString *key in cookieDic) {
            NSString *appendString = [NSString stringWithFormat:@"document.cookie = '%@=%@';", key, [cookieDic valueForKey:key]];
            [cookieValue appendString:appendString];
        }
    }
    return cookieValue;
}

+ (NSString *)getDeviceToken:(NSData *)deviceToken{
    
    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[
                                                                                  NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    return token;

}


static UIImage *_recommedImage;
+ (UIImage *)recommendImage{
    
    CGFloat screenRate = [UIScreen mainScreen].bounds.size.width / 375.0;
    
    if(_recommedImage == nil){
        //31 16
        UIImage *ztImage = nil;
        CGFloat rate = 3;
        CGFloat width = SizeFit(30) * rate * screenRate;
        CGFloat height = SizeFit(14) * rate * screenRate;
        CGFloat fontSize = SizeFit(12) * rate;
        CGFloat x = SizeFit(3) * rate;
        CGFloat y = SizeFit(1) * rate;
        CGFloat rad = SizeFit(3) * rate;
        CGRect rect=CGRectMake(0.0f, 0.0f, width, height);
        UIGraphicsBeginImageContext(rect.size);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetFillColorWithColor(context, [[UIColor clearColor] CGColor]);
        CGContextSetLineWidth(context, 1);
        //UIRectCornerTopLeft
        //CGContextSetStrokeColorWithColor(context, [UIColorFromRGB(0xF62E00) CGColor]);
        //CGContextStrokeRect(context, rect);
        //CGContextFillRect(context, rect);
        
        //24 12
        NSString *str = @"推荐";
        NSDictionary *info = @{
                               NSFontAttributeName: KNFont(fontSize),
                               NSForegroundColorAttributeName:UIColorFromRGB(0xF62E00)
                               };
        [str drawAtPoint:CGPointMake (x, y) withAttributes:info];
        ztImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        
        //圆角处理
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(width, height), NO, 1.0);
        //凤尾
//        [[UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:UIRectCornerBottomRight|UIRectCornerTopLeft|UIRectCornerBottomLeft cornerRadii:CGSizeMake(rad, rad)] addClip];
        [[UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:UIRectCornerBottomRight|UIRectCornerTopLeft|UIRectCornerBottomLeft|UIRectCornerTopRight cornerRadii:CGSizeMake(rad, rad)] addClip];
        [ztImage drawInRect:rect];
        _recommedImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    return _recommedImage;
}

@end
